package com.itcast.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcast.pojo.Collect;
import com.itcast.pojo.Goods;
import com.itcast.pojo.Shoppingcart;
import com.itcast.pojo.User;
import com.itcast.service.Goodsservice;
import com.itcast.service.Shoppingcartservice;
import com.itcast.util.OutUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2020-06-19
 */
@Controller
@RequestMapping("/shoppingcart")
public class ShoppingcartController {
    /**
     * 商品
     */
    @Autowired
    private Goodsservice goodsservice;
    /**
     * 购物车
     */
    @Autowired
    private Shoppingcartservice shoppingcartservice;

    /**
     * 加入购物车
     * @param gid
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value ="/addShopping")
    @ResponseBody
    public String addbay(Integer gid,Integer userId, HttpServletResponse response, HttpSession session) {
        String r ="";
        if (userId != null) {
            int uId = Integer.valueOf(userId);
            Shoppingcart shoppingcart = new Shoppingcart();
            int munber=1;
            Shoppingcart car=shoppingcartservice.getCart(gid, uId);
            Goods s =goodsservice.getById(gid);
            if (car!=null) {
                float tocal=0;
                if (munber>1) {
                    car.setSubtotal(munber+car.getSubtotal());
                    tocal =(float)(car.getTotalCount()+(munber*s.getPrice()));
                    car.setTotalCount(tocal);
                }else {
                    car.setSubtotal(car.getSubtotal()+1);
                    tocal =car.getTotalCount()+s.getPrice();
                    car.setTotalCount(tocal);
                }
                car.setUpDates(new Date());
                boolean result =shoppingcartservice.updateById(car);
                if(result){
                    r ="ok";
                    System.err.println("ok");
                }else{
                    r ="ok";
                    System.err.println("error");
                }
            }else {
                car =new Shoppingcart();
                car.setGid(gid);
                car.setUid(uId);
                if (munber>1) {
                    car.setSubtotal(munber);
                    car.setTotalCount(s.getPrice()*munber);
                }else {
                    car.setSubtotal(1);
                    car.setTotalCount(s.getPrice());
                }
                car.setCreateDate(new Date());
                boolean result =shoppingcartservice.save(car);

                if(result){
                    r ="ok";
                    System.err.println("ok");
                }else{
                    r ="error";
                    System.err.println("error");
                }

            }
        }else {
            r ="err";
            System.err.println("err");
        }
        return r;
    }

    /**
     * 购物车减价
     * @param conditionData
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value ="/reduceShopping")
    @ResponseBody
    public String reduce(@RequestBody Map<String,String> conditionData, HttpServletResponse response, HttpSession session) {
            String r ="";
         int number=Integer.valueOf(conditionData.get("subtotal"))-1;
         Float g_Price=Float.valueOf(conditionData.get("totalPrice"));
         Float tocal=(Float.valueOf(conditionData.get("totalCount")))-g_Price;
        if (number>0) {
            Shoppingcart car =new Shoppingcart();
            QueryWrapper<Shoppingcart> queryWrapper =new QueryWrapper<Shoppingcart>();
            queryWrapper.eq("id",Integer.valueOf(conditionData.get("id")));
            car.setSubtotal(number);
            car.setTotalCount(tocal);
            car.setTotalPrice(g_Price);
            boolean result =shoppingcartservice.update(car,queryWrapper);
            if(result){
                r="ok";
            }else{
                r="error";
            }
        }

        return null;
    }

    /**
     * 添加物品数量
     * @param conditionData
     * @param response
     * @param session
     * @return
     */
    @RequestMapping(value ="/Addsnumber")
    @ResponseBody
    public String Addsnumber(@RequestBody Map<String,String> conditionData, HttpServletResponse response, HttpSession session) {
        String r ="";
        int number=Integer.valueOf(conditionData.get("subtotal"))+1;
        Float g_Price=Float.valueOf(conditionData.get("totalPrice"));
        Float tocal=(Float.valueOf(conditionData.get("totalCount")))+g_Price;
            Shoppingcart car =new Shoppingcart();
            QueryWrapper<Shoppingcart> queryWrapper =new QueryWrapper<Shoppingcart>();
            queryWrapper.eq("id",Integer.valueOf(conditionData.get("id")));
            car.setSubtotal(number);
            car.setTotalCount(tocal);
            car.setTotalPrice(g_Price);
            boolean result =shoppingcartservice.update(car,queryWrapper);
            if(result){
                r="ok";
            }else{
                r="error";
            }

        return null;
    }

    /**
     * 删除商品根据id
     * @param id
     * @param response
     * @param session
     * @return
     */
 @RequestMapping(value ="/del")
 @ResponseBody
public String del(Integer id, HttpServletResponse response, HttpSession session){
    boolean result=shoppingcartservice.removeById(id);
    String r ="";
    if(result){
        r="ok";
    }else{
       r="error";
    }
    return r;
}

    @RequestMapping(value ="/dels")
    @ResponseBody
    public String dels(String idss, HttpServletResponse response, HttpSession session){
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        int result=shoppingcartservice.dels(idss);
        String r ="";
        if(result>0){
            jsonMap.put("flag",true);
            jsonMap.put("count",result);
        }else{
            jsonMap.put("flag",false);
            jsonMap.put("count",0);
        }
        String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
        OutUtil.outcase(json,response);
        return null;
    }



    /**
     *购物车列表
     * @param response
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value ="/listBay")
    public String listBay(HttpServletResponse response, HttpSession session,Integer userId ) {
        List<Shoppingcart> shoppingcartList = null;
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        System.out.println(userId);
        if (userId != null) {
            int uId = Integer.valueOf(userId);
             shoppingcartList =shoppingcartservice.getCartList(uId);
             jsonMap.put("shoppingcartList", shoppingcartList);
             jsonMap.put("msg","ok");
        }else {
           jsonMap.put("msg","no");
       }
        String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
        OutUtil.outcase(json,response);
        return null;
    }

    /**
     * 首页购物车
     * @return
     */
    @ResponseBody
    @RequestMapping("/getListBayIndex")
    public List<Shoppingcart> getListBay(HttpServletResponse response, HttpServletRequest request,@RequestBody Map<String,String> conditionData){
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        System.out.println(conditionData.get("userId"));
        if (conditionData.get("userId") != null) {
            Integer uId = Integer.valueOf(conditionData.get("userId"));
            QueryWrapper<Shoppingcart> ew = new QueryWrapper<>();
            ew.eq("uid", uId );
            ew.select("IFNULL(sum(subtotal),0) AS sum");
            Map<String, Object> map = shoppingcartservice.getMap(ew);
            System.out.println(map);
            String s= map.get("sum").toString();
            List<Shoppingcart> shoppingcartList =shoppingcartservice.getListBay(1);//购物车前两条
            if (shoppingcartList!=null){
                jsonMap.put("shoppingcartList", shoppingcartList);
                jsonMap.put("msg","ok");
                jsonMap.put("sum",map.get("sum"));

            }else {
                jsonMap.put("msg","no");
            }
        }else{
            jsonMap.put("msg","no");
        }
        String json = JSON.toJSONString(jsonMap);//加入fastjson-1.2.13.jar包
        OutUtil.outcase(json,response);

        return null;
    }

    /**
     * 购物车推荐
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getBayType")
    public List<Goods> getBayType(HttpServletResponse response, HttpServletRequest request,Integer userId){

        return null;
    }

}


